package org.jfbmonitor.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import org.jfbmonitor.beans.Attachment;
import org.jfbmonitor.connection.FBConnection;
import org.jfbmonitor.language.Language;

public class AttachmentDao {
	private Statement statement;
	private ResultSet resultSet;
	private StringBuffer listFields;
	
	public AttachmentDao(){
		listFields = new StringBuffer();
		listFields.append("SELECT  A.MON$ATTACHMENT_ID, A.MON$SERVER_PID,");
		listFields.append(" CASE A.MON$STATE");
		listFields.append("  WHEN 0 THEN '"+Language.getInstance().getProperties("MON$STATE.IDLE")+"'");
		listFields.append("  WHEN 1 THEN '"+Language.getInstance().getProperties("MON$STATE.ACTIVE")+"'");		
		listFields.append(" END AS MON$STATE,");
		listFields.append(" A.MON$ATTACHMENT_NAME, A.MON$USER, A.MON$ROLE,");
		listFields.append(" A.MON$REMOTE_PROTOCOL, A.MON$REMOTE_ADDRESS,");
		listFields.append(" A.MON$REMOTE_PID, C.RDB$CHARACTER_SET_NAME,");
		listFields.append(" A.MON$TIMESTAMP, A.MON$GARBAGE_COLLECTION,");
		listFields.append(" A.MON$REMOTE_PROCESS, A.MON$STAT_ID ");
		listFields.append("FROM");
		listFields.append(" MON$ATTACHMENTS A ");
		listFields.append("LEFT JOIN RDB$CHARACTER_SETS C ON A.MON$CHARACTER_SET_ID = C.RDB$CHARACTER_SET_ID");		
	}	
	
	public List<Attachment> getAll( String condition ) throws SQLException{		
		
		if (condition.trim()!="") {
			listFields.append(" where "+condition);
		}		
		statement = FBConnection.getInstance().getConnection().createStatement();		
		resultSet = statement.executeQuery(listFields.toString());
		List<Attachment> list = new ArrayList<Attachment>();
		while (resultSet.next()) {
			list.add( new Attachment( 
					  resultSet.getInt("MON$ATTACHMENT_ID"),
					  resultSet.getInt("MON$SERVER_PID"),					  
					  resultSet.getString("MON$STATE"),
					  resultSet.getString("MON$ATTACHMENT_NAME"),
					  resultSet.getString("MON$USER"),					  
					  resultSet.getString("MON$ROLE"),					  
					  resultSet.getString("MON$REMOTE_PROTOCOL"),					  
					  resultSet.getString("MON$REMOTE_ADDRESS"),					  
					  resultSet.getInt("MON$REMOTE_PID"),
					  resultSet.getString("MON$REMOTE_PROCESS"),					  
					  resultSet.getString("RDB$CHARACTER_SET_NAME"),
					  resultSet.getDate("MON$TIMESTAMP"),
					  resultSet.getShort("MON$GARBAGE_COLLECTION"),
					  resultSet.getInt("MON$STAT_ID")
					)					
            );
		//System.out.println(listFields.toString());	
		}			
		resultSet.getStatement().close();
		return list;
	}	
	

}
